import React, { Component } from "react";
import { connect } from "dva";
import { Row, Col, Card, Tabs, List, Select, Radio, Spin } from "antd";
import moment from "moment";
import numeral from "numeral";
import Icon from "@cbd/icon";
import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  StackedBar
} from "../../components/Charts";
import DateComponent from "../../components/dateComponent";
import { getTimeDistance } from "../../utils/utils";

import styles from "./HomePage.less";

const { TabPane } = Tabs;
const { Option } = Select;
const topColResponsiveProps = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 6,
  style: { marginBottom: 24 }
};

const rankTab = ["scene", "plan"];
const dafaultDate = getTimeDistance("date", 15);

@connect(({ chart, home, user: { department } }) => ({
  chart,
  homeData: home,
  department
}))
export default class HomePage extends Component {
  state = {
    currentRanK: "scene",
    deptCode: "",
    loading: false, // 统计loading
    barLoading: false,
    startDate: dafaultDate[0]
      ? moment(dafaultDate[0]).format("YYYY-MM-DD 00:00:00")
      : "",
    endDate: dafaultDate[0]
      ? moment(dafaultDate[1]).format("YYYY-MM-DD 23:59:59")
      : "",
    mode: "date"
  };

  componentDidMount() {
    const { dispatch, department } = this.props;
    this.setState(
      {
        loading: true,
        deptCode: department
      },
      () => {
        this.getInitData();
      }
    );
    dispatch({
      type: "home/fetchTop4Count",
      payload: {}
    }).then(() => {
      this.setState({
        loading: false
      });
    });
    dispatch({
      type: "chart/fetch"
    });
  }

  componentDidUpdate(prevProps) {
    const { department } = this.props;
    if (prevProps.department !== department && department) {
      this.setState(
        {
          deptCode: department
        },
        () => {
          this.getInitData();
        }
      );
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: "chart/clear"
    });
  }

  getInitData = () => {
    const { dispatch } = this.props;
    const { deptCode } = this.state;
    if (deptCode) {
      dispatch({
        type: "home/fetchDepList",
        payload: { deptCode }
      });
      this.getPushCount();
    }
  };

  getChartData = () => {
    const { startDate, endDate, deptCode, mode } = this.state;
    const { dispatch } = this.props;
    const params = {
      startDate,
      endDate,
      deptCode
    };
    const action = mode === "date" ? "fetchPushDaily" : "fetchPushMonthly";
    dispatch({
      type: "home/fetchPushCount",
      payload: { action, params }
    });
  };

  getPushCount = () => {
    const { startDate, endDate, deptCode } = this.state;
    const { dispatch } = this.props;
    if (!deptCode) return;
    this.setState({
      barLoading: true
    });
    const params = {
      startDate,
      endDate,
      deptCode,
      orderField: "push_count",
      orderType: "desc",
      pageNum: 1,
      pageSize: 7
    };

    Promise.all([
      this.getChartData(),
      dispatch({
        type: "home/fetchSceneRank",
        payload: { ...params }
      }),
      dispatch({
        type: "home/fetchPlanRank",
        payload: { ...params }
      })
    ]).then(() => {
      this.setState({
        barLoading: false
      });
    });
  };

  handleDateChange = (obj = {}) => {
    this.setState(
      {
        startDate: obj.date ? obj.date[0] : "",
        endDate: obj.date ? obj.date[1] : "",
        mode: obj.mode,
        currentRanK: "scene"
      },
      () => {
        this.getPushCount();
      }
    );
  };

  handleSelect = value => {
    const { department } = this.props;
    const deptCode = value || department;
    this.setState(
      {
        deptCode,
        currentRanK: "scene"
      },
      () => {
        this.getPushCount();
      }
    );
  };

  handleRankChange = e => {
    const currentRanK = e.target.value;
    this.setState({
      currentRanK
    });
    const { dispatch } = this.props;
    const { startDate, endDate, deptCode } = this.state;
    if (!deptCode) return;
    const params = {
      startDate,
      endDate,
      deptCode,
      orderField: "push_count",
      orderType: "desc",
      pageSize: 7,
      pageNum: 1
    };
    this.setState({
      barLoading: true
    });
    const type = currentRanK === "scene" ? "fetchSceneRank" : "fetchPlanRank";
    dispatch({
      type: `home/${type}`,
      payload: { ...params }
    }).then(() => {
      this.setState({
        barLoading: false
      });
    });
  };

  render() {
    const {
      loading,
      barLoading,
      currentRanK,
      mode,
      startDate,
      endDate
    } = this.state;
    const {
      chart,
      homeData: {
        datasource = {},
        otherCount = {},
        pushDepList = [],
        pushData = [],
        rankList = []
      } = {}
    } = this.props;
    let pushList = pushData;
    pushList = pushList.slice(0, 15);
    pushList = pushList.map(item => ({
      x: item[`${mode}`],
      y1: item.sendCount,
      y2: item.readCount
    }));
    // 数据源
    const { dsCount = 0, latestDsName, latestDsSubmitTime } = datasource;
    const {
      sendTotalCount = 0,
      sendTodayCount = 0,
      readTotalCount = 0,
      commentTotalCount = 0
    } = otherCount;
    const { visitData } = chart;
    // 反馈率
    const feedbackRate =
      commentTotalCount && sendTotalCount
        ? `${Math.round((commentTotalCount / sendTotalCount) * 100)}%`
        : "0%";
    const viewRate =
      readTotalCount && sendTotalCount
        ? `${Math.round((readTotalCount / sendTotalCount) * 100)}%`
        : "0%";
    return (
      <div className={styles.root}>
        <Row gutter={24}>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="接入数据源数量"
              loading={loading}
              total={() => (
                <div className={styles.totalNum}>
                  <Icon className={styles.icon} type="layers-simple-line" />
                  <span className={styles.num}>
                    {numeral(dsCount).format("0,0")}
                  </span>
                </div>
              )}
              footer={
                <List.Item>
                  <List.Item.Meta title={latestDsName || "暂无数据"} />
                  <div>
                    {latestDsSubmitTime
                      ? moment(latestDsSubmitTime).format("YYYY-MM-DD")
                      : ""}
                  </div>
                </List.Item>
              }
              contentHeight={46}
            >
              <span className={styles.newInfo}>最近接入</span>
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总推送量"
              loading={loading}
              total={numeral(sendTotalCount).format("0,0")}
              footer={
                <Field
                  label="今日推送量"
                  value={numeral(sendTodayCount).format("0,0")}
                />
              }
              contentHeight={46}
            >
              <MiniArea color="#975FE4" data={visitData} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总查看量"
              loading={loading}
              total={numeral(readTotalCount).format("0,0")}
              footer={<Field label="查看率" value={viewRate} />}
              contentHeight={46}
            >
              <MiniBar color="#33ABFB" data={visitData} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总反馈量"
              loading={loading}
              total={numeral(commentTotalCount).format("0,0")}
              footer={<Field label="反馈率" value={feedbackRate} />}
              contentHeight={46}
            >
              <MiniProgress
                strokeWidth={8}
                percent={feedbackRate.split("%")[0]}
              />
            </ChartCard>
          </Col>
        </Row>

        <Card
          title="推送统计"
          extra={<DateComponent onChange={obj => this.handleDateChange(obj)} />}
          bordered={false}
          bodyStyle={{ padding: 0, overflow: "hidden" }}
        >
          <Spin spinning={barLoading}>
            <Row className={styles.pushCard}>
              <Col xs={24} sm={24} md={12} lg={12} xl={16}>
                <div className={styles.pushBar}>
                  <h4>
                    <strong>查看区域</strong>
                  </h4>

                  <Select
                    className={styles.selectDep}
                    onChange={this.handleSelect}
                    allowClear={true}
                    placeholder="请选择归属部门"
                  >
                    {pushDepList.length > 0 ? (
                      pushDepList.map(({ orgId, orgCode, orgName }) => (
                        <Option key={orgId} value={orgCode}>
                          {orgName}
                        </Option>
                      ))
                    ) : (
                      <Option key="empty" disabled>
                        暂无数据！
                      </Option>
                    )}
                  </Select>
                  <StackedBar
                    data={pushList || []}
                    titleMap={{ y1: "推送数量", y2: "查看数量" }}
                    height={298}
                    key={`${startDate}${endDate}`}
                  />
                </div>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8}>
                <div className={styles.pushRank}>
                  <h4>
                    <strong>推送排名</strong>
                  </h4>
                  <Tabs
                    renderTabBar={() => (
                      <Radio.Group
                        value={currentRanK}
                        style={{ marginBottom: 8 }}
                        onChange={this.handleRankChange}
                      >
                        <Radio.Button value="scene">推送场景排名</Radio.Button>
                        <Radio.Button value="plan">推送计划排名</Radio.Button>
                      </Radio.Group>
                    )}
                    activeKey={currentRanK}
                  >
                    {rankTab.length > 0 &&
                      rankTab.map((tab, index) => (
                        <TabPane key={tab}>
                          <ul className={styles.rankingList}>
                            {rankList[index] &&
                              rankList[index].length > 0 &&
                              rankList[index].slice(0, 7).map((item, i) => (
                                <li key={i}>
                                  <span className={i < 3 ? styles.active : ""}>
                                    {i + 1}
                                  </span>
                                  <span
                                    title={item.templateName || item.planName}
                                  >
                                    {item.templateName || item.planName}
                                  </span>
                                  <span>
                                    {numeral(item.sendCount).format("0,0")}
                                  </span>
                                </li>
                              ))}
                          </ul>
                        </TabPane>
                      ))}
                  </Tabs>
                </div>
              </Col>
            </Row>
          </Spin>
        </Card>
      </div>
    );
  }
}
